/**
 * 用户服务 - 管理用户状态和权限
 */
import { ElMessage } from 'element-plus';
import router from '../router';
import axios from 'axios';
import { reactive, ref } from 'vue';

// 创建axios实例
const api = axios.create({
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  },
  validateStatus: status => status >= 200 && status < 300
});

// 请求拦截器，自动加token
api.interceptors.request.use(config => {
  const token = localStorage.getItem('token') || (currentUser && currentUser.token) || '';
  if (token) {
    config.headers.token = token;
  }
  return config;
});

// 响应拦截器
api.interceptors.response.use(
  (response) => {

    return response
  },
  (error) => {
    //如果响应的状态码为401, 则路由到登录页面
    console.log('响应错误:', error);
    if (error.response.status === 401) {
      ElMessage.error('登录失效, 请重新登录')
      router.push('/login')
    } else {
      ElMessage.error('接口访问异常')
    }
    return Promise.reject(error)
  }
);

// 当前用户信息 - 默认管理员，可通过修改此处切换用户身份
let currentUser = {
  userId: null, // 1为管理员，其他为普通用户
  username: '',
  isAdmin: false,
  token: ''
};

const message = ref(null);

const UserService = {
  /**
   * 获取当前用户ID
   * @returns {Number} 用户ID
   */
  getCurrentUserId() {
    return currentUser.userId;
  },

  /**
   * 获取当前用户名
   * @returns {String} 用户名
   */
  getCurrentUsername() {
    return currentUser.username;
  },

  /**
   * 判断当前用户是否为管理员
   * @returns {Boolean} 是否为管理员
   */
  isAdmin() {
    return currentUser.isAdmin;
  },

  /**
   * 获取当前用户完整信息
   * @returns {Object} 用户信息
   */
  getCurrentUser() {
    return { ...currentUser };
  },

  loadCurrentUser() {

    const currentUserStr = localStorage.getItem('currentUser');
    let nowUserId = null;
    let userRole = null;
    let userName = null;
    let userToken = null;

    if (currentUserStr) {
      try {
        nowUserId = JSON.parse(currentUserStr).userId;
        userRole = JSON.parse(currentUserStr).userType;
        userName = JSON.parse(currentUserStr).userName;
        userToken = JSON.parse(currentUserStr).token;

      } catch {
        nowUserId = null;
        userRole = null;
        userName = null;
        userToken = null;
      }
    }

    currentUser.userId = nowUserId;
    currentUser.username = userName;
    currentUser.isAdmin = userRole === 2 ? true : false;
    currentUser.token = userToken;

  },

  //登录
  async login(username, password) {
    try {

      const user = reactive(
        {
          userName: username,
          password: password

        }
      );
      const response = await api.post('/api/user/login', user);
      console.log('登录成功:asd', response.data);
      message.value = response.data.message;
      const { token } = response.data;
      console.log(response.data.data.userId);
      currentUser.userId = response.data.data.userId;
      currentUser.username = response.data.data.userName;
      currentUser.isAdmin = response.data.data.userId === 2 ? true : false;
      currentUser.token = token;
      localStorage.setItem('token', token);
      return response.data;
    } catch (error) {
      console.error('登录失败:', message.value);
      throw message.value;
    }
  },

  // 退出登录
  async logout() {
    try {
      const response = await api.post('/api/user/logout');
      localStorage.removeItem('token');
      localStorage.removeItem('currentUser');
      currentUser.token = '';
      return response.data;
    } catch (error) {
      console.error('退出登录失败:', error);
      throw error;
    }
  },

  // 分页查询用户
  async getUserList(params = {}) {
    try {
      const response = await api.get('/api/user/list', { params });
      return response.data;
    } catch (error) {
      console.error('获取用户列表失败:', error);
      throw error;
    }
  },

  // 根据部门查找用户
  async getUserListByDepts(deptIds, page = 1, size = 10) {
    try {
      const response = await api.post(`/api/user/byDepartmentIds?page=${page}&size=${size}`, deptIds);
      return response.data;
    } catch (error) {
      console.error('获取用户列表失败:', error);
      throw error;
    }
  },

  // 新增用户
  async addUser(data) {
    try {
      const response = await api.post('/api/user/add', data);
      return response.data;
    } catch (error) {
      console.error('新增用户失败:', error);
      throw error;
    }
  },

  // 更新用户
  async updateUser(userId, data) {
    try {
      console.log(data);
      const response = await api.put(`/api/user/${userId}`, data);
      console.log(response.data);
      return response.data;
    } catch (error) {
      console.error('更新用户失败:', error);
      throw error;
    }
  },

  // 更新自身信息
  async updateProfile(userId, data) {
    try {
      console.log(data);
      const response = await api.put(`/api/user/own/${userId}`, data);
      console.log(response.data);
      localStorage.removeItem('currentUser');
      localStorage.setItem('currentUser', JSON.stringify(response.data.data));
      return response.data;
    } catch (error) {
      console.error('更新用户失败:', error);
      throw error;
    }
  },

  // 重置密码
  async changePassword(req) {
    try {
      console.log(req);
      const response = await api.post(`/api/user/updatePassword`, req);
      return response.data;
    } catch (error) {
      console.error('重置密码失败:', error);
      throw error;
    }
  },

  // 删除用户
  async deleteUser(userId) {
    try {
      const response = await api.delete(`/api/user/${userId}`);
      return response.data;
    } catch (error) {
      console.error('删除用户失败:', error);
      throw error;
    }
  },

  // 查询单个用户
  async getUserDetail(userId) {
    try {
      const response = await api.get('/api/user/byUserId', { params: { userId } });
      return response.data;
    } catch (error) {
      console.error('获取用户详情失败:', error);
      throw error;
    }
  },

  //按部门查询用户列表
  async getUserByDept(departmentId) {
    try {
      const response = await api.get('/api/user/byDepartment', { params: { departmentId } });
      return response.data;
    } catch (error) {
      console.error('获取用户列表失败:', error);
      throw error;
    }
  },

  // 获取岗位列表
  async getPositionList() {
    try {
      const response = await api.get('/api/position/list');
      return response.data;
    } catch (error) {
      console.error('获取岗位列表失败:', error);
      throw error;
    }
  },

  // 获取角色列表
  async getRoleList() {
    try {
      const response = await api.get('/api/role/list');
      return response.data;
    } catch (error) {
      console.error('获取角色列表失败:', error);
      throw error;
    }
  }
};



export default UserService; 